 
let { createCanvas } = require('canvas') ;
let drawBlock = require('./cores/drawBlock');
let drawImage = require('./cores/drawImage');
let drawLine = require('./cores/drawLine');
let drawText = require('./cores/drawText');
let { getHeight } = require('./cores/tool');


/**
 * CanvasDarwPoster : 创建海报类
 * 流程
 *   1.初始化数据创建view
 *   2.获取获取视图节点，通过数据绘制视图
 *   3.通过cratePosterImage方法生成一张图片
 */
class CanvasDarwPoster {
  constructor(config) {
    this.config = config;
     this.ctx = null
    this.canvas = null
  }
  init() {
    return new Promise(async v => {
         this.initData();
         this.initContext(); //初始化上下文
      await this.initDraw(); //初始化画布界面
      v(this)
    })
  }
  
  //获取上下文对象
  initContext() {
      let { width, height } = this.config;
      const canvas = createCanvas(width, height)
      const ctx = canvas.getContext('2d')
      this.ctx = ctx;
      this.canvas = canvas;

  }
  //生成图片
  cratePosterImage() {
    // const base64 = this.canvas.toBuffer('image/jpeg', { quality: 0.5 })
    let data = this.canvas.toDataURL("image/jpeg", 1);
    // const base64 = data.replace(/^data:image\/\w+;base64,/, '');

    return data
  }
  //根据数据初始化海报界面
  initDraw() {
    return new Promise(async v => {

      let options = { ctx: this.ctx, canvas: this.canvas, pixelRatio: 1 };
      // 设置画布底色
      if (this.config.backgroundColor) {
       
        this.ctx.save();
        this.ctx.fillStyle = this.config.backgroundColor;
        this.ctx.fillRect(0, 0, this.config.width, this.config.height);
        this.ctx.restore();
      }

      let drawListCount = [];
      //循环渲染所以的属性列表
      let drawNameList = [
        { name: "blocks", method: drawBlock },
        { name: "texts", method: drawText },
        { name: "images", method: drawImage },
        { name: "lines", method: drawLine },
      ];
      console.log('befored:', this.config);
      drawNameList.map((attr) => {
        this.config[attr.name] && this.config[attr.name].map((item) => {
          let { zIndex = null, ...leftover } = item;
          drawListCount.push({
            key: zIndex,
            run: () => attr.method({ options, data: { ...leftover } }),
          });
        });
      });
      //根据zindex进行排序 && 开始绘画

      // drawListCount.sort((a, b) => a.key - b.key).forEach(async item => {await item.run();console.log(item)})
      let sortArr = drawListCount.sort((a, b) => a.key - b.key);
      //按顺序同步执行
      for (let i = 0; i < sortArr.length; i++) {
        await sortArr[i].run();
      }
      console.log('after:', this.config);

      v()
    })
  }
 //海报清晰度倍数
  toPx(num) {
    let {pixelRatio} = this.config
    return num  * pixelRatio;
  }

  initData() {
    let that = this
    let config = this.config;
    config.height = getHeight(config)
    config.canvasId = config.canvasId || 'canvas-' + Math.floor(Math.random() * 1000)
    //需要转换尺寸的属性
    let toPxAttrs = ["width", "height", "fontSize", "y", "x", 'lineHeight', 'borderRadius',];

    function judType(data, type) {
      let val = Object.prototype.toString.call(data);
      if (type === 'base') {
        return true

      } else if (type === 'object') {
        return val === '[object Object]'

      } else if (type === 'array') {
        return val === '[object Array]'

      }
    }
    function proData(data, prent, attr) {
      if (judType(data, 'object')) {
        let obj = {}
        Object.keys(data).map(attr => {
          obj[attr] = proData(data[attr], data, attr)
        })
        return obj
      } else if (judType(data, 'array')) {
        let array = []
        data.map((item, index) => {
          array[index] = proData(item)
        })
        return array
      } else if (toPxAttrs.includes(attr)) {
        return that.toPx(data);
      } else {
        return data;
      };
    }
    config = proData(config);
    this.config = config;
    return config;
  }
}

module.exports = CanvasDarwPoster;
